﻿
using Catalog.API.Expections;

namespace Catalog.API.Products.UpdateProduct
{
    public record UpdateProductResult(bool IsSuccess);
    public record UpdateProductCommand(Guid Id, string Name, string Description, decimal Price, string ImageFile, List<string> Categories)
        : ICommand<UpdateProductResult>;


    public class UpdateProductCommandValidator : AbstractValidator<UpdateProductCommand>
    {
        public UpdateProductCommandValidator()
        {
            RuleFor(x => x.Id).NotEmpty().WithMessage("Id cannot be empty.");
            RuleFor(x => x.Name).NotEmpty().WithMessage("Name cannot be empty.");
            RuleFor(x => x.Description).NotEmpty().WithMessage("Description cannot be empty.");
            RuleFor(x => x.Price).GreaterThan(0).WithMessage("Price cannot be empty.");
            RuleFor(x => x.ImageFile).NotEmpty().WithMessage("ImageFile cannot be empty.");
            RuleFor(x => x.Categories).NotEmpty().WithMessage("Categories cannot be empty.");
        }
    }
    internal class UpdateProductCommandHandler(IDocumentSession session)
        : ICommandHandler<UpdateProductCommand, UpdateProductResult>
    {
        public async Task<UpdateProductResult> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
        {
            
            var product = await session.LoadAsync<Product>(request.Id);
            if (product == null)
            {
                throw new ProductNotFoundException($"Product with id: {request.Id} not found.");
            }
            product.Name = request.Name;
            product.Description = request.Description;
            product.Price = request.Price;
            product.ImageFile = request.ImageFile;
            product.Categories = request.Categories;
            session.Update(product);
            await session.SaveChangesAsync(cancellationToken);
            return new UpdateProductResult(true);
        }
    }
}
